package net.sinmetal.twitcockpit.controller.cockpit;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.sinmetal.twitcockpit.exception.TwitterRuntimeException;
import net.sinmetal.twitcockpit.twitter.Twitter4tc;
import net.sinmetal.twitcockpit.twitter.Twitter4tcFactory;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.AppEngineUtil;

import twitter4j.Query;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Tweet;

/**
 * CockpitIndexController
 *
 * @author Sinmetal
 *
 */
public class IndexController extends Controller {

    private static final Logger logger = Logger.getLogger(IndexController.class
        .getName());

    /**
     * Twitter Tweet を表示
     */
    @Override
    public Navigation run() throws Exception {
        String twitterID = "test4sinmetal";
        if (AppEngineUtil.isProduction()) {
            twitterID = "chugokugtug";
        }

        Twitter4tc twitter4tc = new Twitter4tcFactory().getInstance(twitterID);
        requestScope("homeTimeLine", getHomeTimeLine(twitter4tc));
        requestScope("mentions", getMention(twitter4tc));
        requestScope(
            "chugokugtugHashTweets",
            getChugokugtugHashTweets(twitter4tc));

        return forward("index.jsp");
    }

    /**
     * HomeTimeLine取得
     *
     * @param twitter
     * @return
     */
    private ResponseList<Status> getHomeTimeLine(Twitter4tc twitter) {
        ResponseList<Status> homeTimeLine;
        try {
            homeTimeLine = twitter.getHomeTimeline();
        } catch (TwitterRuntimeException e) {
            homeTimeLine = null;
            logger.log(Level.SEVERE, "twitter-error", e);
        }
        return homeTimeLine;
    }

    /**
     * Mention 取得
     *
     * @param twitter
     * @return
     */
    private ResponseList<Status> getMention(Twitter4tc twitter) {
        ResponseList<Status> mentions;
        try {
            mentions = twitter.getMentions();
        } catch (TwitterRuntimeException e) {
            mentions = null;
            logger.log(Level.SEVERE, "twitter-error", e);
        }
        return mentions;
    }

    /**
     * ChugokugtugHashTweets 取得
     *
     * @param twitter
     * @return
     */
    private List<Tweet> getChugokugtugHashTweets(Twitter4tc twitter) {
        Query query = new Query("#chugokugtug");
        query.setResultType(Query.RECENT);

        List<Tweet> chugokugtugHashTweets;
        try {
            chugokugtugHashTweets = twitter.search(query);
        } catch (TwitterRuntimeException e) {
            chugokugtugHashTweets = null;
            logger.log(Level.SEVERE, "twitter-error", e);
        }
        return chugokugtugHashTweets;
    }
}
